import React from 'react';
import PropTypes from 'prop-types';
import { Button, Form, Upload, message } from 'antd';
// import { getDvaApp } from 'umi';
import { UploadOutlined } from '@ant-design/icons';
import { onBeforeUpload, preViewFile } from './util';
import localStorage from '../utils/localStorage';
import { getConfigure } from '../utils/configure'; // 获取默认配置

const FormItem = Form.Item;
// 上传文件
/*
 * 输出到外面的数据结构
 * */
export const onNormFile = (uploadingFilesNow, e) => {
  const { fileList } = e;
  if (Array.isArray(e)) {
    return e;
  }
  // 并发操作处理
  fileList.forEach((res, index) => {
    if (!onBeforeUpload(res, fileList, 1)) {
      uploadingFilesNow(false);
      fileList.splice(index, 1);
    }
    if (fileList.length > 50) {
      uploadingFilesNow(false);
      message.error('最多只能上传50个文件!');
      fileList.splice(50, fileList.length - 1);
    }

    if (res.status === 'done') {
      uploadingFilesNow(true);
      if (res.response && res.response.success !== 1) {
        message.error(res.response.message);
        fileList.splice(index, 1);
      }

      if (res.response && res.response.success === 1) {
        // 上传成功
        // todo 新项目，这里可能要改（因为数据结构可能不一样）
        message.success(res.response.message);
        fileList.splice(index, 1, {
          uid: res.uid,
          name: res.name,
          fileName: res.name,
          fileCode: res.response.models[0].code,
          fileId: res.response.models[0].id,
        });
      }
      if (
        res.response &&
        res.response.success === 0 &&
        res.response.resultCode === '00999'
      ) {
        setTimeout(() => {
          // getDvaApp()._store.dispatch({ type: 'login/logout' });
        }, 800);
      }
    }
  });

  return fileList;
};
function Index(props) {
  const { uploadingFilesNow = () => {} } = props;
  return (
    <FormItem
      {...props}
      valuePropName="fileList"
      getValueFromEvent={(e) => {
        return onNormFile(uploadingFilesNow, e);
      }}
      extra="支持扩展名：.rar .zip .doc .docx .pdf .jpg"
    >
      <Upload
        listType="text"
        disabled={props.disabled}
        action={getConfigure().uploadApi}
        headers={{
          Client: getConfigure().client,
          Authorization: localStorage.getItem('token'),
        }}
        beforeUpload={onBeforeUpload}
        onPreview={preViewFile}
      >
        <Button disabled={props.disabled}>
          <UploadOutlined /> 上传文件
        </Button>
      </Upload>
    </FormItem>
  );
}
/*
 * 其他参数 和FormItem组件一致
 *
 * */
Index.propTypes = {
  label: PropTypes.string,
  name: PropTypes.string,
};
export default React.memo(Index);
